package com.Jshop.goods.service;

import com.Jshop.goods.utils.ThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 静态化
 * */
@Service
public class GoodHtmlService {


    @Autowired
    private GoodsService goodsService;

    //模板引擎
    @Autowired
    private TemplateEngine templateEngine;

    private static final Logger LOGGER = LoggerFactory.getLogger(GoodHtmlService.class);

    //创建html页面
    public void createHtml(Long spuId){

        PrintWriter writer = null;
        try {
            //获取页面数据
            Map<String, Object> spuMap = this.goodsService.loadData(spuId);
            //创建thymeleaf上下文对象
            Context context = new Context();
            //把数据放入上下文对象
            context.setVariables(spuMap);
            //创建输出流
//            File file = new File("C:\\nginx-1.14.0\\html\\item\\" + spuId + ".html");
            File file = new File("/usr/local/etc/nginx/html/item/" + spuId + ".html");
            System.out.println("CREATE FILE" + spuId + ".HTML");
            writer = new PrintWriter(file);

            //执行页面静态化方法
            templateEngine.process("item",context,writer);

        }catch (Exception e){
            LOGGER.error("静态化出错：{}," + e, spuId);
        }finally {
            if (writer != null){
                writer.close();
            }
        }
    }

    //新建线程处理页面静态化
    public void asyncExcute(Long spuId) {
        ThreadUtils.execute(() -> createHtml(spuId));
    }

    public void deleteHtml(Long id) {
        File file = new File("/usr/local/etc/nginx/html/item/" + id + ".html");
        file.deleteOnExit();
    }
}
